package cn.edu.lingnan.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

@RestController
public class CaptchaController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/common/verify")
public void verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // 获取当前用户的会话ID
    String sessionId = request.getSession().getId();
    // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
    ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 4, 1);
    // 使用会话ID作为键名，将验证码存储到Redis中，120秒后自动删除
    redisTemplate.opsForValue().set("captcha:" + sessionId, captcha.getCode(), Duration.ofSeconds(120));
    // 将验证码图片写出到响应流中
    response.setContentType("image/jpeg");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    // 图形验证码写出到流
    captcha.write(response.getOutputStream());
    // 设置成功响应头
    response.setStatus(200);
    System.out.println("验证码：" + captcha.getCode());
}

}
